﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Windows.Forms;

namespace UIShare
{
    public static class FormOpener
    {
        private static Hashtable _openedForms = new Hashtable();

        public static Form MainForm { get; set; }

        public static void ShowMdiChild(Form frm)
        {
            ShowMdiChild(frm, null);
        }

        public static void ShowMdiChild(Form frm, string uniqueKey)
        {
            if (MainForm != null)
            {
                frm.MdiParent = MainForm;
            }

            initForm(frm);

            bool isOpened = checkIsOpened(frm, uniqueKey);

            if (!isOpened)
                frm.Show();
        }

        public static void ShowForm(Form frm)
        {
            ShowForm(frm, null);
        }

        public static void ShowForm(Form frm, string uniqueKey)
        {
            if (MainForm != null)
            {
                frm.Owner = MainForm;
            }

            initForm(frm);

            bool isOpened = checkIsOpened(frm, uniqueKey);

            if (!isOpened)
                frm.Show();
        }

        public static DialogResult ShowDialog(Form frm)
        {
            if (MainForm != null)
            {
                frm.Owner = MainForm;
            }

            initForm(frm);

            return frm.ShowDialog();
        }

        private static void initForm(Form frm)
        {
            frm.Icon = MainForm.Icon;
            frm.StartPosition = FormStartPosition.CenterScreen;
        }

        private static bool checkIsOpened(Form frm, string uniqueKey)
        {
            if (string.IsNullOrEmpty(uniqueKey))
            {
                return false;
            }


            if (_openedForms.ContainsKey(uniqueKey))
            {
                ((Form)_openedForms[uniqueKey]).Activate();
                return true;
            }


            _openedForms.Add(uniqueKey, frm);
            frm.FormClosed += (s, e) =>
            {
                _openedForms.Remove(uniqueKey);
            };


            return false;
        }

        public static void Reload()
        {

        }
    }
}
